package info.ensa.model;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
 
import info.ensa.model.Personne;
 
public class XMLPullParserHandler {
    List<Personne> personnes;
    private Personne personne;
    private String text;
 
    public XMLPullParserHandler() {
    	personnes = new ArrayList<Personne>();
    }
 
    public List<Personne> getEmployees() {
        return personnes;
    }
 
    public List<Personne> parse(InputStream is) {
        XmlPullParserFactory factory = null;
        XmlPullParser parser = null;
        try {
            factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            parser = factory.newPullParser();
 
            parser.setInput(is, null);
 
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagname = parser.getName();
                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (tagname.equalsIgnoreCase("employee")) {
                        // create a new instance of employee
                    	personne = new Personne();
                    }
                    break;
 
                case XmlPullParser.TEXT:
                    text = parser.getText();
                    break;
 
                case XmlPullParser.END_TAG:
                    if (tagname.equalsIgnoreCase("employee")) {
                        // add employee object to list
                    	personnes.add(personne);
                    } else if (tagname.equalsIgnoreCase("nom")) {
                    	personne.setNom(text);
                    } else if (tagname.equalsIgnoreCase("age")) {
                    	personne.setAge(Integer.parseInt(text));
                    } else if (tagname.equalsIgnoreCase("adresse")) {
                    	personne.setAdresse(text);
                    }
                    break;
 
                default:
                    break;
                }
                eventType = parser.next();
            }
 
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return personnes;
    }
}